using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Adex;
using MediaMonitor.Common;
using System.Net;
using System.Data;

namespace MediaMonitor
{
    public partial class Login : Adex.BasePage
    {
        protected void page_load(Object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string retUrl = null;
                retUrl = Utility.GetRequestedVal("ReturnUrl", "");
                HyperLink lnkReg = this.loginx.FindControl("lnkReg") as HyperLink;
                string heading = null;
                if (!string.IsNullOrEmpty(retUrl))
                {
                    if (retUrl.Contains("/users/"))
                    {
                        heading = "User's login required";
                        if ((lnkReg != null))
                            lnkReg.NavigateUrl = Utility.AppPath + "/register.aspx?type=3&returnUrl=" + retUrl;
                    }
                    else if (retUrl.Contains("/client/"))
                    {
                        heading = "Company's login required";
                        if ((lnkReg != null))
                            lnkReg.NavigateUrl = Utility.AppPath + "/register.aspx?type=2&returnUrl=" + retUrl;
                    }
                    else if (retUrl.Contains("/admin/"))
                    {
                        heading = "Admin's login required";
                        if ((lnkReg != null))
                            lnkReg.NavigateUrl = Utility.AppPath + "/register.aspx?type=1&returnUrl=" + retUrl;
                    }
                    else
                    {
                        heading = "User's login required";
                        if ((lnkReg != null))
                            lnkReg.NavigateUrl = Utility.AppPath + "/register.aspx?type=3&returnUrl=" + retUrl;
                    }
                }
                else
                {
                    heading = "User's login required";
                    if ((lnkReg != null))
                        lnkReg.NavigateUrl = Utility.AppPath + "/register.aspx?type=3&returnUrl=" + retUrl;
                }
                this.ltrHeading.Text = heading;
            }
        }
        protected void login_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e)
        {
            string userName = loginx.UserName;
            string password = loginx.Password;
            bool rememberUserName = loginx.RememberMeSet;
            ReportFuncs rep = new ReportFuncs();
            Int32 UserID = 0; Boolean IsLoggedIn;
            MembershipUser user = Membership.GetUser(loginx.UserName);
            if (System.Web.Security.Membership.ValidateUser(loginx.UserName, loginx.Password))
            {
                SiteUser usr = AppUser.GetUserByUserName(loginx.UserName);
                if (usr.SiteUserID > 0)
                {
                    AppUser.SignIn(usr.SiteUserID, loginx.RememberMeSet);
                    UserID = usr.SiteUserID;
                    Session["UserID"] = UserID;
                    Session["Company"] = usr.Company;
                    Session["CompanyCode"] = usr.CompanyCode;
                    Session["UserName"] = usr.UserName;
                    Session["email"] = usr.Email;
                    DataTable dt = rep.GetUserIDAndRolle(Session["UserID"].ToString());
                    Session["UserRole"] = dt.Rows[0][2].ToString();
                    if (user != null && user.LastPasswordChangedDate.Date.AddDays(90) < DateTime.Now.Date && dt.Rows[0][2].ToString() != "admin")
                    {
                        string script = "alert(\"Your password has expired, please contact AGB Team to set a new one!\");";
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);
                        return;
                    }
                    HttpCookie NoSummary = new HttpCookie("NoSummary");
                    NoSummary.Value = GetCompanyNoSummary(Convert.ToInt32(usr.CompanyCode));
                    NoSummary.Expires = DateTime.Now.AddHours(24);
                    Response.Cookies.Add(NoSummary);
                    // Create forms authentication ticket
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1, // Ticket version
                    userName,// Username to be associated with this ticket
                    DateTime.Now, // Date/time ticket was issued
                    DateTime.Now.AddMinutes(50), // Date and time the cookie will expire
                    rememberUserName, // if user has chcked rememebr me then create persistent cookie
                     Session["UserRole"].ToString(), // store the user data, in this case roles of the user
                    FormsAuthentication.FormsCookiePath); // Cookie path specified in the web.config file in <Forms> tag if any.
                    // To give more security it is suggested to hash it
                    string hashCookies = FormsAuthentication.Encrypt(ticket);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies); // Hashed ticket
                    // Add the cookie to the response, user browser
                    Response.Cookies.Add(cookie);
                    IsLoggedIn = Convert.ToBoolean(usr.IsLoggedIn);
                    if ((Request["ReturnUrl"] != null))
                    {
                        String Val = Server.UrlDecode(Request["ReturnUrl"]).ToString();
                        if (Val.Contains("users") || Val.Contains("Users"))
                        {
                            if (UserID > 0)
                                SaveLoginUserDetails(UserID);
                        }
                        SqlDataSource1.UpdateParameters.Add("SiteUserID", UserID.ToString());
                        SqlDataSource1.Update();
                        Response.Redirect(Request["ReturnUrl"]);
                    }
                    else
                    {
                        if (UserID > 0)
                        {
                            SaveLoginUserDetails(UserID);
                        }
                        Response.Redirect("~/users/default.aspx");
                    }
                }
                else
                {
                    string script = "alert(\"Invalid Username (or Password)!\");";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);
                    
                }
            }
            else
            {
                AjaxFuncs.LoginScreen(this.Page, true);
            }
        }


        private void SaveLoginUserDetails(Int32 UserID)
        {
            String stringIpAddress = String.Empty;
            //Get IP Address
            stringIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (stringIpAddress == null) //may be the HTTP_X_FORWARDED_FOR is null
            {
                stringIpAddress = Request.ServerVariables["REMOTE_ADDR"];//we can use REMOTE_ADDR
            }
            if (!String.IsNullOrEmpty(stringIpAddress))
            {
                RfController.SiteUser_Insert(UserID, stringIpAddress);
            }
        }
        private string GetCompanyNoSummary(int companyCode)
        {
            string Nosumary = (SPs.GetCompanyNoSummary(companyCode).ExecuteScalar()).ToString();
            return Nosumary;
        }

    }//end class
}
